package com.shchuangzhi.smartguard.core.command;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.shchuangzhi.smartguard.core.Consts;
import com.shchuangzhi.smartguard.core.Grade;
import com.shchuangzhi.smartguard.core.NotifyMessage;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by j_hu on 5/10/17.
 */

public class SyncGradeHandler extends SyncMetaCommandRespHandler {
    public SyncGradeHandler(SyncMetaCommand cmd) {
        super("grade.sync", cmd);
    }

    @Override
    public boolean handle(InputStream input) {
        boolean handleOk = false;
        try {
            Gson gson = new Gson();
            SyncMetaCommandRS<SyncGradeListRS> syncRS = (SyncMetaCommandRS<SyncGradeListRS>)gson.fromJson(
                    getString(input),
                    new TypeToken<SyncMetaCommandRS<SyncGradeListRS>>(){}.getType());
            if (syncRS != null && syncRS.getData().getList() != null) {
                getCommand().notify(NotifyMessage.info(
                        String.format("%s<%s>", Consts.INFO_SYNC_GRADE, syncRS.getData().getList().size()), Consts.NOTIFY_DATA_SYNC, Consts.NOTIFY_DATA_SYC_VIEW_LIST));

                ArrayList<Grade> list = new ArrayList<>();
                for(GradeRS g:syncRS.getData().getList()) {
                    Grade grade = new Grade(this.getCommand().getDbHelper());
                    grade.setNO(g.getNo());
                    grade.setName(g.getName());
                    list.add(grade);
                }
                if (getCommand().getDbHelper().groupAddGrades(list)) {
                    getCommand().getDbHelper().getSyncRecord().update(getName(), syncRS.getLastMetaUpdateTime());
                    getCommand().notify(NotifyMessage.info(
                            String.format("%s<%s>", Consts.INFO_SYNC_GRADE_OK, syncRS.getData().getList().size()), Consts.NOTIFY_DATA_SYNC, Consts.NOTIFY_DATA_SYC_VIEW_LIST));
                    handleOk = true;
                } else {
                    getCommand().notify(NotifyMessage.info(
                            String.format("%s<%s>", Consts.INFO_SYNC_GRADE_FAIL, syncRS.getData().getList().size()), Consts.NOTIFY_DATA_SYNC, Consts.NOTIFY_DATA_SYC_VIEW_LIST));
                }
            }
        }catch(Exception e) {
            getCommand().raiseError(e);
        }
        return handleOk;
    }

    public class SyncGradeListRS {
        private List<GradeRS> list;
        public List<GradeRS> getList() {
            return list;
        }
    }

    public class GradeRS {
        private int no;
        private String name;

        public int getNo() {
            return no;
        }
        public String getName() {
            return name;
        }
    }
}
